package com.example.controller;

import com.example.model.Inventory;
import com.example.repository.InventoryRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/wash/inventory")
@Tag(name = "库存管理", description = "库存物品的创建、查询、更新和管理")
public class InventoryController {
    
    @Autowired
    private InventoryRepository inventoryRepository;

    @PostMapping
    @Operation(summary = "创建库存物品")
    public ResponseEntity<Inventory> createInventoryItem(@Valid @RequestBody Inventory inventory) {
        Inventory createdItem = inventoryRepository.save(inventory);
        return ResponseEntity.ok(createdItem);
    }

    @GetMapping
    @Operation(summary = "获取库存列表")
    public ResponseEntity<Page<Inventory>> getAllInventory(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "itemName") String sortBy,
            @RequestParam(defaultValue = "asc") String sortDir,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) Boolean lowStock) {
        
        Sort sort = Sort.by(Sort.Direction.fromString(sortDir), sortBy);
        Pageable pageable = PageRequest.of(page, size, sort);
        
        if (category != null && !category.isEmpty()) {
            try {
                Inventory.ItemCategory itemCategory = Inventory.ItemCategory.valueOf(category.toUpperCase());
                return ResponseEntity.ok(inventoryRepository.findByCategory(itemCategory, pageable));
            } catch (IllegalArgumentException e) {
                return ResponseEntity.badRequest().build();
            }
        }
        
        return ResponseEntity.ok(inventoryRepository.findAll(pageable));
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取库存物品详情")
    public ResponseEntity<Inventory> getInventoryDetail(@PathVariable Long id) {
        return inventoryRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新库存物品")
    public ResponseEntity<Inventory> updateInventoryItem(
            @PathVariable Long id,
            @Valid @RequestBody Inventory inventory) {
        return inventoryRepository.findById(id)
                .map(existingItem -> {
                    inventory.setId(id);
                    Inventory updatedItem = inventoryRepository.save(inventory);
                    return ResponseEntity.ok(updatedItem);
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除库存物品")
    public ResponseEntity<Void> deleteInventoryItem(@PathVariable Long id) {
        if (inventoryRepository.existsById(id)) {
            inventoryRepository.deleteById(id);
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.notFound().build();
    }

    @GetMapping("/low-stock")
    @Operation(summary = "获取库存不足的物品")
    public ResponseEntity<List<Inventory>> getLowStockItems() {
        List<Inventory> lowStockItems = inventoryRepository.findLowStockItems();
        return ResponseEntity.ok(lowStockItems);
    }

    @GetMapping("/expiring")
    @Operation(summary = "获取即将过期的物品")
    public ResponseEntity<List<Inventory>> getExpiringItems(
            @RequestParam(defaultValue = "30") int days) {
        LocalDateTime expiryDate = LocalDateTime.now().plusDays(days);
        List<Inventory> expiringItems = inventoryRepository.findExpiringItems(expiryDate);
        return ResponseEntity.ok(expiringItems);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索库存物品")
    public ResponseEntity<List<Inventory>> searchInventory(@RequestParam String name) {
        List<Inventory> items = inventoryRepository.findByItemNameContaining(name);
        return ResponseEntity.ok(items);
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取库存统计信息")
    public ResponseEntity<Map<String, Object>> getInventoryStatistics() {
        List<Object[]> categoryStats = inventoryRepository.countByCategory();
        Double totalValue = inventoryRepository.getTotalInventoryValue();
        Long lowStockCount = inventoryRepository.countLowStockItems();
        
        Map<String, Object> statistics = Map.of(
            "categoryStatistics", categoryStats,
            "totalValue", totalValue != null ? totalValue : 0.0,
            "lowStockCount", lowStockCount,
            "totalItems", inventoryRepository.count()
        );
        
        return ResponseEntity.ok(statistics);
    }

    @PutMapping("/{id}/stock")
    @Operation(summary = "更新库存数量")
    public ResponseEntity<Inventory> updateStock(
            @PathVariable Long id,
            @RequestBody Map<String, Object> stockUpdate) {

        Optional<Inventory> inventoryOpt = inventoryRepository.findById(id);
        if (inventoryOpt.isPresent()) {
            Inventory inventory = inventoryOpt.get();
            Integer newStock = (Integer) stockUpdate.get("currentStock");
            String operation = (String) stockUpdate.get("operation"); // "add", "subtract", "set"

            if (newStock != null) {
                switch (operation != null ? operation : "set") {
                    case "add":
                        inventory.setCurrentStock(inventory.getCurrentStock() + newStock);
                        break;
                    case "subtract":
                        inventory.setCurrentStock(Math.max(0, inventory.getCurrentStock() - newStock));
                        break;
                    case "set":
                    default:
                        inventory.setCurrentStock(newStock);
                        break;
                }

                // 如果是补货操作，更新补货时间
                if ("add".equals(operation)) {
                    inventory.setLastRestockDate(LocalDateTime.now());
                }

                Inventory updatedInventory = inventoryRepository.save(inventory);
                return ResponseEntity.ok(updatedInventory);
            }
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.notFound().build();
    }
}
